package com.guogz.pic.sevice.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class UploadServiceImpl implements UploadService {
	private Logger logger = LoggerFactory.getLogger(UploadServiceImpl.class);

	@Value("${images.path}")
	private String remotepath;
	
	@Override
	public List<String> uploadPic(HttpServletRequest request, String uploadPath) {

		// ip + 时间来存储图片
		String requestIp = request.getRemoteAddr().replaceAll(".", "");

		// 图片路径的集合
		List<String> paths = new ArrayList<String>();
		try {
			Iterator<Part> iterator = request.getParts().iterator();
			while (iterator.hasNext()) {
				// logger.info("多少个字节 {}",iterator.next().getSize());
				Part part = iterator.next();

				String time = part.getSubmittedFileName();
				String realName = part.getName();
				String suffix = realName.substring(realName.lastIndexOf('.'));
				String newFileName = requestIp + time + suffix;

				String path = uploadPath + newFileName;
				
				String realPath = remotepath + newFileName;
				part.write(path);

				paths.add(realPath);

				logger.info("==== 输出图片 === {} ,", path);
			}
		} catch (Exception e) {
			logger.error("[图片上传失败 IllegalStateException] ", e);
			return paths;
		}

		return paths;
	}

}
